package com.ultisense.gassensor;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.ColorStateList;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

public class RoomActivity extends AppCompatActivity {

    private static final int PERMISSION_REQUEST_COARSE_LOCATION = 1;
    @BindView(R.id.greet1)
    TextView greet1;
    @BindView(R.id.greet2)
    TextView greet2;
    @BindView(R.id.icon_title)
    ImageView iconTitle;
    @BindView(R.id.navigation2)
    BottomNavigationView navigation2;
    @BindView(R.id.content)
    FrameLayout content;
    @BindView(R.id.container)
    LinearLayout container;

    final List<Fragment> fragments = new ArrayList<>();

    private void createView() {
        greet1 = findViewById(R.id.greet1);
        greet2 = findViewById(R.id.greet2);
        iconTitle = findViewById(R.id.icon_title);

        navigation2 = findViewById(R.id.navigation2);
        Resources resource = getResources();
        ColorStateList csl = resource.getColorStateList(R.color.selector_navigation_text);
//        Drawable bg=resource.getDrawable(R.drawable.selector_navigation_background);
        navigation2.setItemTextColor(csl);
//        navigation2.setItemBackground(bg);

        content = findViewById(R.id.content);
        container = findViewById(R.id.container);

        fragments.add(RoomFragment.newInstance());
        fragments.add(SourceFragment.newInstance());

        iconTitle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Intent intent=new Intent(RoomActivity.this,RoomScreenActivity.class);
                startActivity(intent);
            }
        });
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_room);
        ButterKnife.bind(this);
//        FontsOverride.setDefaultFont(this, "DEFAULT", "roboto_light.ttf");
        createView();

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            // Android M Permission check
            if (this.checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, PERMISSION_REQUEST_COARSE_LOCATION);
            }
        }
        if (findViewById(R.id.content) != null) {
            // However, if we're being restored from a previous state,
            // then we don't need to do anything and should return or else
            // we could end up with overlapping fragments.
            if (savedInstanceState != null) {
                return;
            }
            // Create an instance of BtActivity
            RoomFragment RoomFrag = new RoomFragment();
            // In case this activity was started with special instructions from an Intent,
            // pass the Intent's extras to the fragment as arguments
            RoomFrag.setArguments(getIntent().getExtras());
            // Add the fragment to the 'fragment_container' FrameLayout
            getSupportFragmentManager().beginTransaction()
                    .add(R.id.content, RoomFrag, "RoomFragment").commit();
            initChart();
        }
        //setup navigation bar
//        navigation2.setOnTabSelectedListener(mOnTabSelectedListener);
        navigation2.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
    }

//    private TabLayout.OnTabSelectedListener mOnTabSelectedListener=new TabLayout.OnTabSelectedListener() {
//        @Override
//        public void onTabSelected(TabLayout.Tab tab) {
//            Log.e("TAG","tab position:"+tab.getPosition());
//            replaceFragment(fragments.get(tab.getPosition()));
//        }
//
//        @Override
//        public void onTabUnselected(TabLayout.Tab tab) {
//
//        }
//
//        @Override
//        public void onTabReselected(TabLayout.Tab tab) {
//
//        }
//    };

    private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
            = new BottomNavigationView.OnNavigationItemSelectedListener() {

        @Override
        public boolean onNavigationItemSelected(@NonNull MenuItem item) {
            Fragment selectedFragment = null;
            FragmentManager manager = getSupportFragmentManager();
            if (item.getItemId() == R.id.navigation_home) {
                FragmentTransaction transaction = manager.beginTransaction();
                if (manager.findFragmentByTag("RoomFragment") == null) {
                    selectedFragment = new RoomFragment();
                    transaction.replace(R.id.content, selectedFragment, "RoomFragment");
                } else {
                    selectedFragment = manager.findFragmentByTag("RoomFragment");
                    transaction.replace(R.id.content, selectedFragment);
                }
                transaction.addToBackStack(null);
                transaction.commit();
            } else if (item.getItemId() == R.id.navigation_source) {
                FragmentTransaction transaction = manager.beginTransaction();
                if (manager.findFragmentByTag("SourceFragment") == null) {
                    selectedFragment = new SourceFragment();
                    transaction.replace(R.id.content, selectedFragment, "SourceFragment");
                } else {
                    selectedFragment = manager.findFragmentByTag("SourceFragment");
                    transaction.replace(R.id.content, selectedFragment);
                }
                transaction.addToBackStack(null);
                transaction.commit();
            }
            return true;
        }

    };

    public void initChart() {
        int baseline = 0;
        int sensorNum = 5;
        int maxLevel = 8000;
        int criticalLevel = 160;
        // User touched the dialog's positive button
        RoomFragment Roomfrag = (RoomFragment) getSupportFragmentManager().findFragmentById(R.id.content);

        if (Roomfrag != null) {
            Roomfrag.setSensorNum(sensorNum);
            Roomfrag.setBaseSignal(baseline);
            Roomfrag.setMaxLevel(maxLevel);
            Roomfrag.setCriticalLevel(criticalLevel);
            Roomfrag.initGraph();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
        switch (requestCode) {
            case PERMISSION_REQUEST_COARSE_LOCATION:
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // TODO request success
                }
                break;
        }
    }
}
